#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/ip.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/stat.h>
#define ARGS_CHECK(argc, num)               \
    {                                       \
        if (argc != num)                    \
        {                                   \
            fprintf(stderr, args error !n); \
            return -1;                      \
        }                                   \
    }
#define ERROR_CHECK(ret, num, msg) \
    {                              \
        if (ret == num)            \
        {                          \
            perror(msg);           \
            exit(1);               \
        }                          \
    }
int main(int argc, char *argv[])
{
    signal(SIGPIPE, SIG_IGN);
    int fd_s = socket(PF_INET, SOCK_STREAM, 0);
    ERROR_CHECK(-1, fd_s, "socket");
    struct sockaddr_in saddr;
    saddr.sin_family = PF_INET;
    saddr.sin_port = htons(8889);
    saddr.sin_addr.s_addr = inet_addr("0");
    int ret = bind(fd_s, (void *)&saddr, sizeof saddr);
    ERROR_CHECK(-1, ret, "bind");
    ret = listen(fd_s, 2);
    ERROR_CHECK(-1, ret, "listen");
    puts("listen ...");
    char buf[1024];
    char len[5] = {0};
    while (1)
    {

        int fd_new = accept(fd_s, NULL, NULL);
        if (-1 == fd_new)
        {
            continue;
        }
        puts("connected");
        int fd_file = open("img1.png", O_RDONLY);
        if (-1 == fd_file)
        {
            continue;
        }
        while (1)
        {
            ret = read(fd_file, buf, 1024);
            sprintf(len, "%d", ret);
            write(fd_new, len, 5);
            if (0 == ret)
                break;

            write(fd_new, buf, ret);
        }
        close(fd_file);
        close(fd_new);
    }

    return 0;
}
